import { defineStore } from 'pinia'
import Cookies from 'js-cookie'
import { computed, ref, toRaw } from 'vue'
import router, { pageRoutes } from '@/router'
import _ from 'lodash'

export const useMenuStore = defineStore(
  'menu',
  () => {
    // state
    const opened = ref(Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : false)
    const withoutAnimation = ref(false)
    const openKeys = ref([])
    const selectedKeys = ref([])
    const menuData = ref([])

    // getter
    const getMenus = computed(() => {
      let routes = router.options.routes
      return [...routes, ...toRaw(menuData.value)]
    })

    //action
    // 更改侧边栏的伸缩状态
    const toggleSideBar = () => {
      opened.value = !opened.value
      withoutAnimation.value = false
      if (opened.value) {
        Cookies.set('sidebarStatus', 1)
      } else {
        Cookies.set('sidebarStatus', 0)
      }
    }

    // 添加动态路由
    const addAsyncRoutes = (menus) => {
      // 获取pageRoutes（页面路由表）
      const localRoutes = _.cloneDeep(pageRoutes)
      // 获取用户具有的权限
      // 对pageRoutes进行权限判定
      const authMenuTree = matchingRoute(menus, localRoutes)
      authMenuTree.push({
        path: '/:pathMatch(.*)',
        //访问主页的时候 重定向到404页面
        redirect: '/404',
        hidden: true
      })
      // 将最终的路由进行动态添加
      authMenuTree.forEach((item) => {
        router.addRoute(item)
      })
      menuData.value = authMenuTree
    }
    // 给pageRoutes进行权限判定
    const matchingRoute = (menus, localRoutes) => {
      let list = []
      localRoutes.forEach((item) => {
        if (!item.meta['isPermission'] || isOwnPermission(menus, item.name)) {
          if (item.children) {
            item.children = matchingRoute(menus, item.children)
          }
          list.push(item)
        }
      })
      return list
    }
    const isOwnPermission = (menus, title) => {
      return menus.includes(title)
    }

    return {
      opened,
      withoutAnimation,
      openKeys,
      selectedKeys,
      menuData,
      getMenus,
      toggleSideBar,
      addAsyncRoutes
    }
  },
  {
    persist: true
  }
)
